package com.spbdx.common.core.redis;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * Description redis锁
 *
 * @author chenwei
 * @version 1.0
 * @date 2023/2/21 11:28
 */
@Component
public class RedisLock {

    @Resource
    private RedisTemplate redisTemplate;

    private static final String DEVICE_KEY = "device_key:";

    private static final Long LOCK_REDIS_TIMEOUT = 60L;


    /**
     * 锁住设备
     *
     * @param id
     * @param value
     * @return
     */
    public Boolean getLockDevice(String id, String value) {
        Boolean lockStatus = this.redisTemplate.opsForValue().setIfAbsent(DEVICE_KEY + id, value, LOCK_REDIS_TIMEOUT, TimeUnit.SECONDS);
        System.out.println("getLockDevice=" + lockStatus);
        return lockStatus;
    }

    /**
     * 释放设备
     *
     * @param id
     * @param value
     */
    public Long releaseLockDevice(String id, String value) {
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
        Long releaseStatus = (Long) this.redisTemplate.execute(redisScript, Collections.singletonList(DEVICE_KEY + id), value);
        return releaseStatus;
    }

}
